package com.jackrain.clouddata.oms.services;/**
 * Created by Administrator on 2017/3/28.
 */

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.clouddata.oms.dao.LogStageDao;
import com.jackrain.clouddata.oms.util.ExceptionUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.util.ApplicationContextHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Description:
 * Created with IntelliJ IDEA.
 * User: cs
 * Date: 2017/3/28
 * Time: 10:05
 */

@Service
@Slf4j
public class SendSMSServies {

    @Autowired
    private PropertiesConf pconf;

    private FastDateFormat fastformat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");


    public  void sendSMS(JSONObject senderContext){
        String accessKey=pconf.getProperty("ons.accessKey");
        String secretKey=pconf.getProperty("ons.secretKey");
        String Endpoint=pconf.getProperty("ons.mnsendpoint");
        String mnstopic=pconf.getProperty("ons.mnstopic");
        String smsphone=pconf.getProperty("oms.smsphone");
        String smstemp=pconf.getProperty("oms.smstemp");
        String company=pconf.getProperty("ons.comp");
        String sing=pconf.getProperty("ons.sign");

        /**
         * Step 1. 获取主题引用
         */
        CloudAccount account = new CloudAccount(accessKey, secretKey, Endpoint);
        MNSClient client = account.getMNSClient();
        CloudTopic topic = client.getTopicRef(mnstopic);
        /**
         * Step 2. 设置SMS消息体（必须）
         *
         * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
         */
        RawTopicMessage msg = new RawTopicMessage();
        msg.setMessageBody("sms-message");
        /**
         * Step 3. 生成SMS消息属性
         */
        MessageAttributes messageAttributes = new MessageAttributes();
        BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
        // 3.1 设置发送短信的签名（SMSSignName）
        batchSmsAttributes.setFreeSignName(sing);
        // 3.2 设置发送短信使用的模板（SMSTempateCode）
        batchSmsAttributes.setTemplateCode(smstemp);
        // 3.3 设置发送短信所使用的模板中参数对应的值（在短信模板中定义的，没有可以不用设置）
        BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
        smsReceiverParams.setParam("company", company);
        smsReceiverParams.setParam("errmsg", shorten(senderContext.getString("errmsg"),50,"..."));
        smsReceiverParams.setParam("protime", fastformat.format(System.currentTimeMillis()));
        smsReceiverParams.setParam("clientip", NetUtils.getLocalAddress().getHostAddress().replace(".","-"));
        // 3.4 增加接收短信的号码

        if(smsphone.trim().indexOf(",")>0){
            String[] phones=smsphone.split(",");
            for(int i=0;i<phones.length;i++) {
                System.out.println(phones[i]);
                batchSmsAttributes.addSmsReceiver(phones[i], smsReceiverParams);
            }
        }else{
            batchSmsAttributes.addSmsReceiver(smsphone, smsReceiverParams);
        }
        //batchSmsAttributes.addSmsReceiver(smsphone, smsReceiverParams);
        //batchSmsAttributes.addSmsReceiver("18818200818", smsReceiverParams);
        //batchSmsAttributes.addSmsReceiver("$YourReceiverPhoneNumber2", smsReceiverParams);
        messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
        try {
            /**
             * Step 4. 发布SMS消息
             */
            TopicMessage ret = topic.publishMessage(msg, messageAttributes);
            System.out.println("MessageId: " + ret.getMessageId());
            System.out.println("MessageMD5: " + ret.getMessageBodyMD5());
        } catch (ServiceException se) {
            System.out.println(se.getErrorCode() + se.getRequestId());
            System.out.println(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        client.close();
    }


    /**
     *  length will include suffix's length, for instance,
     *  shorten("abcd", 3, "..") = "a.."
     *
     */
    public static String shorten(String s, int length, String suffix) {
        if (s == null || suffix == null)  {
            return null;
        }

        if (s.length() > length) {
            s = s.substring(0, length- suffix.length())  + suffix;
        }

        return s;
    }



}
